/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    InteractionManager
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import defaultService from '../lib/services/defaultService';
import StorageUser from '../lib/plugins/StorageUser';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class InformationDetails extends Component{
    constructor(props) {
        super(props);
        this.userId = '';
        this.state = {
            personId:this.props.navigation.state.params.personId,
            token:this.props.navigation.state.params.token,
            personData:{},
            petList:[],
        }; 
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.userId){
                    $this.userId = data.userId;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getPersonDetails();
                });              
            }).catch(err=> {
                console.log(err)
            });
    }

    renderAnimals(){
        var list = this.state.petList;
        var len = list.length;
        if(len==0){
            return(
                <View></View>
            )
        }else if(len>0&&len<=2){
            return(
                list.map((item,i)=>{
                    return(
                        <TouchableOpacity key={i} onPress={()=>this.goAnimalDetails(item.id)}>
                            <AnimalItem icon={{uri:'http://test.520m.com.cn/upload/thumb/'+item.img}} name={item.pet_name||''} rank={item.pet_grade||1} typeText={item.cate_name||''}/>
                        </TouchableOpacity>
                    )
                })
            )
        }else if(len>2){
            return(
                list.map((item,i)=>{
                    return(
                        <View style={{marginLeft:20}} key={i}>
                            <TouchableOpacity onPress={()=>this.goAnimalDetails(item.id)}>
                            <ImageWrapper style={{borderRadius:20,width:40,height:40}} icon={{uri:'http://test.520m.com.cn/upload/thumb/'+item.img}}/>
                            </TouchableOpacity>
                        </View>
                    )
                })
            )
        }
    }

    renderAnimalList(){
        var len = this.state.petList.length;
        if(len==0){
            return(
                <View></View>
            )
        }else if(len>0&&len<=2){
            return(
                <View style={{padding:10}}>
                     {this.renderAnimals()}   
                </View>
            )
        }else if(len>2){
            return(
                <ScrollView style={{paddingTop:20,paddingBottom:20,paddingRight:20}} horizontal={true}>
                    {this.renderAnimals()}
                </ScrollView>
            )
        }
    }

    render(){
        // officer体验官1普通2初级3高级
        // foster 寄养0不是寄养1是寄养
        var data = this.state.personData;
        var sexArr = ['','男','女'];
        var date = new Date().getFullYear();
        var age = '';
        if(data.birth_time){
            age = (date - new Date(parseInt(data.birth_time)*1000).getFullYear() +'') || '未填写';
        }
        var personId = data.id;
        // alert(date)
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'详细信息'} 
                    leftPress={()=>this.goBack()}
                    rightIcon={this.state.personData.is_friend?'':'add'}
                    rightPress={()=>this.goAddFriend(personId)}
                    rightStyle={{marginRight:10}}/>
                <ScrollView>
                    <View style={{padding:10,backgroundColor:'#fff'}}>
                        <Image source={data.user_head_img?{uri:'http://test.520m.com.cn/upload/common/'+data.user_head_img}:require('../img/icon/touxiang.png')} style={{width:width-20,height:width-20,justifyContent:'flex-end'}}>
                            <View style={{flexDirection:'row',alignItems:'center',paddingLeft:10,paddingRight:10,paddingTop:5,paddingBottom:5,width:width-20}}>
                                <View style={{alignItems:'center',flexDirection:'row'}}>
                                    <Text style={{color:'#333',fontSize:18,marginLeft:10}}>{data.username}</Text>
                                    <ImageWrapper icon={'v'} width={16} height={16} style={{marginLeft:5}}/>
                                    <Text style={{fontFamily:'symbol',color:'#f4ea2a',fontSize:18}}>{data.grade}</Text>
                                    {/**{data.officer?<ImageWrapper icon={'touxiang'}/>:<View></View>}
                                    {data.foster?<ImageWrapper icon={'touxiang'}/>:<View></View>}**/}
                                </View>
                            </View>
                        </Image>
                    </View>
                        {this.renderAnimalList()}
                        <InfoItem title={'性别'} text={sexArr[data.sex]}/>
                        <InfoItem title={'年龄'} text={'未填写'}/>
                        <InfoItem title={'个人签名'} text={data.signature||'未填写'}/>
                        <InfoItem title={'地区'} text={data.city_name||'未填写'}/>
                        <InfoItem title={'宠物数'} text={data.pet_nums||'0'} staturs={true}/>
                </ScrollView>
            </View>
        )
    }

    goBack(){
        this.props.navigation.goBack();
    }

    goAddFriend(friendId){
        if(this.userId==this.state.personData.id){
            alert('不能添加自己为好友！');
            return;
        }
        var $this = this;
        const {navigate} = this.props.navigation;
        navigate('AddFriend',{friendId:friendId,token:$this.state.token});
    }

    goAnimalDetails(id){
        var $this = this;
        const {navigate} = this.props.navigation;
        navigate('AnimalDetails',{animalId:id,token:$this.state.token});
    }

    getPersonDetails(){
        var $this = this;
        defaultService.randomDetail(function(data){  
            // alert(JSON.stringify(data));          
            if(data.code==10000){
                var obj = data.data;
                var len = obj.pet_imgs?obj.pet_imgs.length:0;
                var list = [];
                if(len==0){
                    list = [];
                }else if(len==1){
                    var object = obj.pet_imgs[0];
                    object.pet_name = obj.pet_name[0].pet_name||'';
                    object.pet_sex = obj.pet_sex[0].pet_sex||0;
                    object.pet_grade = obj.pet_grade[0].pet_grade||1;
                    list.push(object);
                }else if(len==2){
                    list = obj.pet_imgs;
                    for(var i=0;i<2;i++){
                        if (obj.pet_name) {
                            for(var j=0;j<obj.pet_name.length;j++){
                                if(obj.pet_name[j].id==list[i].id){
                                    list[i].pet_name = obj.pet_name[j].pet_name;
                                    break;
                                }
                            }
                        }
                        if(obj.pet_sex){
                            for(var j=0;j<obj.pet_sex.length;j++){
                                if(obj.pet_sex[j].id==list[i].id){
                                    list[i].pet_sex = obj.pet_sex[j].pet_sex;
                                    break;
                                }
                            }
                        }
                        if(obj.pet_grade){
                            for(var j=0;j<obj.pet_grade.length;j++){
                                if(obj.pet_grade[j].id==list[i].id){
                                    list[i].pet_grade = obj.pet_grade[j].pet_grade;
                                    break;
                                }
                            }
                        }
                        if(obj.cate_name){
                            for(var j=0;j<obj.cate_name.length;j++){
                                if(obj.cate_name[j].id==list[i].id){
                                    list[i].cate_name = obj.cate_name[j].cate_name;
                                    break;
                                }
                            }
                        }
                    }
                }else if(len>2){
                    list = obj.pet_imgs;
                }
                // alert(JSON.stringify(list))
                $this.setState({
                    personData:data.data,
                    petList:list
                })
            }
        },$this.state.personId,$this.state.token)
    }
}

class InfoItem extends Component{
    render(){
        var staturs = this.props.staturs;
        return(
            <View style={{justifyContent:'center',paddingLeft:10,backgroundColor:'#fff'}}>
                <View style={staturs?styles.noBorder:styles.hasBorder}>
                    <Text style={{color:'#333',fontSize:16}}>{this.props.title}</Text>
                    <Text style={{color:'#b1b1b1'}}>{this.props.text}</Text>
                </View>
            </View>
        )
    }
}

class AnimalItem extends Component{
    render(){   
        return(
            <View style={{flexDirection:'row',alignItems:'center',paddingRight:10,paddingLeft:5,paddingTop:5,paddingBottom:5,backgroundColor:'#fff'}}>
                <View>
                    <ImageWrapper style={{width:50,height:50,borderRadius:25}} icon={this.props.icon}/>
                </View>
                <View style={{flex:1,marginLeft:10}}>
                    <View style={{flexDirection:'row'}}>
                        <Text>{this.props.name}</Text>
                        <ImageWrapper icon={'v'}/>
                        <Text>{this.props.rank}</Text>
                    </View>
                    <View>
                        <Text>{this.props.typeText}</Text>
                    </View>
                </View>
                <View>
                    <ImageWrapper icon={'right'}/>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    },
    listTitle:{
    	height:30,
    	justifyContent:'center',
    	paddingLeft:5,
    	paddingLeft:5
    },
    hasBorder:{
        height:40,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'space-between',
        paddingRight:10,
        borderBottomWidth:1,
        borderBottomColor:'#666'
    },
    noBorder:{
        height:40,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'space-between',
        paddingRight:10,
    }
    
    
});